<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class post extends MY_Controller {
	function __construct(){
		parent::__construct();
	}
	function index($start = 0) {
		$this->load->model('post_model','postModel');
		$this->load->model('images_model','imagesModel');
		$this->load->model('type_model','typeModel');
		$this->load->library('pagination');
		
		//config pagination
		$config['prev_link'] = '&laquo;';
    $config['prev_tag_open'] = '<li>';
    $config['prev_tag_close'] = '</li>';

    $config['next_link'] = '&raquo;';
    $config['next_tag_open'] = '<li>';
    $config['next_tag_close'] = '</li>';

    $config['num_tag_open'] = '<li>';
    $config['num_tag_close'] = '</li>';

    $config['cur_tag_open'] = '<li class="active"><a href="#">';
    $config['cur_tag_close'] = '</a></li>';

    $config['first_tag_open'] = '<li>';
    $config['first_tag_close'] = '</li>';

    $config['last_tag_open'] = '<li>';
    $config['last_tag_close'] = '</li>';

    //get all the URI segments for pagination and sorting
    $segment_array = $this->uri->segment_array();
    $segment_count = $this->uri->total_segments();

		$config['base_url'] = base_url('post');
		$whereCount["status"] = 1;
		$config['total_rows'] = $this->postModel->count_rows($whereCount);
		$config['per_page'] = 20;

		//getting the records and limit setting
    if (ctype_digit($segment_array[$segment_count])) {
			$where['limit']['amount'] = $config['per_page'];
			if($segment_array[$segment_count] > 0){
				$where['limit']['start'] = $segment_array[$segment_count];
			}else{
				$where['limit']['start'] = 0;
			}
      $start_offset = ($segment_array[$segment_count]+1);
      $end_offer = ($segment_array[$segment_count]+$config['per_page']);
      if($end_offer > $config['total_rows']){
        $end_offer = $config['total_rows'];
      }
      array_pop($segment_array);
    } else {
      $where['limit']['amount'] = $config['per_page'];
      $where['limit']['start'] = 0;
      $start_offset = 1;
    }
    
    $config['uri_segment'] = count($segment_array)+1;
		$where['where']['status'] = 1;
		$where["order"] = "update_date DESC";
		$posts = $this->postModel->get($where);
		
    if((count($posts)+1) > $start_offset){
      $end_offer = count($posts);
    }

		$this->pagination->initialize($config);

    $this->_assign("end_offset",$end_offer);
    $this->_assign("start_offset",$start_offset);
		$this->_assign('posts',$posts);
		$this->_fetch('index');
	}

	function view($url = "") {

		//Cache post data
		if(!$result = $this->cache->get("postview/postview_".md5($url)."/data_".md5($url))){
			$where['where']['url'] = urldecode($url);
			$where['where']['status'] = 1;
			$result = $this->postModel->get($where);

			if(empty($result)){
				show_404();
			}
			$result = array_merge($result,$this->ion_auth->user_array($result[0]["usr_id"]));
			if(empty($result)){
				show_404();
			}

			$this->cache->write($result,"postview/postview_".md5($url)."/data_".md5($url),(3600*24));
		}
		//end Cache post data

		//update view
		$dataUpdateView["id"] = $result[0]["id"];
		$dataUpdateView["view"] = ($result[0]["view"]+1);
		$updateViewResult = $this->postModel->add($dataUpdateView);
		if(!$updateViewResult) {
			log_message('error', 'can\'t update view in post at '.__FILE__.' line ['.__LINE__.']');
		}
		//end update view

		//Assign to view
		$this->_assign('post',$result[0]);

		//Cache type
		if(!$type = $this->cache->get("postview/postview_".md5($url)."/type_".md5($url))){
	    $this->load->model('type_model','typeModel');
			$gettype['where']['id'] = $result[0]['typ_id'];
			$type = $this->typeModel->get($gettype);
			$this->cache->write($type,"postview/postview_".md5($url)."/type_".md5($url),(3600*24));
		}
		$this->_assign('type',$type);
		//End Cache type


		//Cache images
		if(!$imagesList = $this->cache->get("postview/postview_".md5($url)."/images_".md5($url))){
			$this->load->model('images_model','imagesModel');
			$whereImg['where']['pos_id'] = $result[0]['id'];
			$imagesList = $this->imagesModel->get($whereImg);
			$this->cache->write($imagesList,"postview/postview_".md5($url)."/images_".md5($url),(3600*24));
		}
		//End Cache images

		if(!empty($imagesList)){
			foreach($imagesList as $image){
				if($image["firstimage"]){
					$this->_assign('first_images',$image);
				}
				$images[$image['group']][] = $image;
			}
			$this->_assign('images',$images);
		}
		
		
		//Cache comment
		//if(!$dataCom = $this->cache->get("postview/postview_".md5($url)."/comment_".md5($url))){
			$this->load->model("comment_model","commentModel");
			$wherepos['where']['pos_id'] = $result[0]["id"];
			$wherepos['where']['status'] = 1;
			$wherepos['order'] = "id ASC";
			$dataCom = $this->commentModel->get($wherepos);
			//$this->cache->write($dataCom,"postview/postview_".md5($url)."/comment_".md5($url),(3600*24));
		//}
		//End Cache comment

		$this->_assign("comments",$dataCom);
		if(empty($dataCom)){
			$this->_assign("comment_count",0);
		}else{
			$this->_assign("comment_count",count($dataCom));
		}
		

		//Cache PostMeta
		if(!$postMeta = $this->cache->get("postview/postview_".md5($url)."/postmeta_".md5($url))){
			$postMeta = Util::getPostMeta($result[0]["id"]);
			$this->cache->write($postMeta,"postview/postview_".md5($url)."/postmeta_".md5($url),(3600*24));
		}
		$this->_assign('postmeta',$postMeta);
		//End Cache PostMeta

		//Check postMeta[brand] is exist
		if(!empty($postMeta['brand'])){
			//Cache Brand
			if(!$brand = $this->cache->get("postview/postview_".md5($url)."/brand_".md5($url))){
				$this->load->model("brand_model","brandModel");
				$whereBrand['where']['id'] = $postMeta['brand'];
				$brand = $this->brandModel->get($whereBrand);
				if(!empty($brand)){
					//Keyword Assign
					$keywords[] = $brand[0]["name"];
				}
				$this->cache->write($brand,"postview/postview_".md5($url)."/brand_".md5($url),(3600*24));
			}
			$this->_assign("brand",$brand);
			//End Cache Brand
		}

		//Check postMeta[model] is exist
		if(!empty($postMeta['model'])){
			//Cache Model
			if(!$model = $this->cache->get("postview/postview_".md5($url)."/model_".md5($url))){
				$this->load->model("model_model","modelModel");
				$whereModel['where']['id'] = $postMeta['model'];
				$model = $this->modelModel->get($whereModel);
				if(!empty($model)){
					//Keyword Assign
					$keywords[] = $model[0]["name"];
				}
				$this->cache->write($model,"postview/postview_".md5($url)."/model_".md5($url),(3600*24));
			}
			$this->_assign("model",$model);
			//End Cache Model
		}


		//================= Cache Free =======================================///

		$categories = array_reverse(Util::getCategoryInherit($result[0]["cat_id"]));
		$breadcrumb = "<a href=\"".base_url()."\">หน้าแรก</a> &raquo; <a href=\"".base_url("post")."\">ประกาศทั้งหมด</a>";

		foreach ($categories as $key => $value) {
			$urlCat[] = $value["url"];
			$keywords[] = $value["name"];
			$breadcrumb .= " &raquo; <a href=\"".base_url("category/".implode("/", $urlCat))."\">".$value["name"]."</a>";
		}
		$this->_assign("breadcrumb",$breadcrumb." &raquo; <a href=\"".base_url("post/view/".$result[0]["url"])."\">".$result[0]["title"]."</a>");

		//get keyword
		$configKeywordList = $this->config->item("seo");
		for($i=0;(count($keywords)<10 AND !empty($configKeywordList["keyword"][$i]));$i++){
			$keywords[] = $configKeywordList["keyword"][$i];
		}
		$keywords = implode(", ", $keywords);

		$this->_assign("metaKeyword",$keywords);

		$this->_assign("userdata",$this->ion_auth->user_array());

		$this->_fetch('view');
	}

	function add($id=""){
		if(!$this->ion_auth->logged_in()){
			redirect(base_url("user/login"),"refresh");
		}

		$this->load->model('images_model','imagesModel');
		$userdata = $this->ion_auth->user_array();
		$this->_assign("userdata",$userdata);

		if(!empty($id)){
			$result = $this->postModel->get($id);
			$this->_assign('post',$result);
			if($result[0]["usr_id"] == $userdata['id'] OR ($this->ion_auth->in_group("admin"))){
				$this->load->model('type_model','typeModel');
				$whereType["order"] = 'CONVERT( typ_name USING tis620 ) ASC';
				$type = $this->typeModel->get($whereType);
				$this->_assign('types',$type);

				//new
				$this->load->model('images_model','imagesModel');
				$whereImage["where"]["pos_id"] = $id;
				$imgs = $this->imagesModel->get($whereImage);

				$this->_assign('imgs',$imgs);
				//กำหนดตัวแปร
				for($i=1;$i<=7;$i++){
					$image_detail_group[$i] = NULL;
				}

				/*check firstimg  if ==0  add firstimg auto*/
				$checkfirstimage = true;
				if(!empty($imgs)){
					foreach($imgs as $picfirstimg) :
					if($picfirstimg['firstimage'] == 1) {
						$checkfirstimage = FALSE;
					}
					endforeach;
					if($checkfirstimage == true){
						$_postmeta['id'] = $imgs[0]['id'];
						$_postmeta['firstimage'] = 1;
						$this->imagesModel->add($_postmeta);
					}
				}
				if(!empty($imgs)){
					foreach ($imgs as $key => $value) {
						if(!empty($value['group'])){
							$image_detail_group[$value['group']][] = $value;
						}
					}
				}

				$this->_assign("image_detail_group",$image_detail_group);

				//Get PostMeta
				$postMeta = Util::getPostMeta($id);
				$this->_assign('postmeta',$postMeta);

				unset($where);
				$this->load->model('category_post_model','categoryPostModel');
				$this->load->model('category_model','categoryModel');
				$where["where"]["parent_id"] = 0;
				$where["order"] = "sort ASC";
			 	$result = $this->categoryModel->get($where);
			 	unset($where);
			 	foreach ($result as $key => $value) {
			    $categories[0]['items'][$value['id']] = $value;
			    $categories[0]['parents'][$value['parent_id']][] = $value['id'];
			 	}
			 	$where["where"]["pos_id"] = $id;
			 	$where["select"][] = "cat_id";
			 	$categoryPostList = $this->categoryPostModel->get($where);
			 	$this->_assign('categoriesSelected',$categoryPostList);

			 	foreach ($categoryPostList as $key => $value) {
			 		foreach ($categories[0]['items'] as $key2 => $value2) {
			 			if($value["cat_id"] == $value2["id"]){
			 				$categoryIdLevel1 = $value["cat_id"];
			 				unset($categoryPostList[$key]);
			 			}
			 		}
			 	}
			 	if(!empty($categoryIdLevel1)){
				 	$categoryListLevel2 = Util::getSubCategory($categoryIdLevel1);
				 	if(!empty($categoryListLevel2)){
						foreach ($categoryListLevel2 as $key => $value) {
					    $categories[1]['items'][$value['id']] = $value;
					    $categories[1]['parents'][$value['parent_id']][] = $value['id'];
					 	}
					 	foreach ($categoryPostList as $key => $value) {
					 		foreach ($categoryListLevel2 as $key2 => $value2) {
					 			if($value["cat_id"] == $value2["id"]){
					 				$categoryIdLevel2 = $value["cat_id"];
					 				unset($categoryPostList[$key]);
					 			}
					 		}
					 	}
				 	}
			 	}
			 	if(!empty($categoryIdLevel2)){
				 	$categoryListLevel3 = Util::getSubCategory($categoryIdLevel2);
				 	if(!empty($categoryListLevel3)){
					 	foreach ($categoryListLevel3 as $key => $value) {
					    $categories[2]['items'][$value['id']] = $value;
					    $categories[2]['parents'][$value['parent_id']][] = $value['id'];
					 	}
					 	foreach ($categoryPostList as $key => $value) {
					 		foreach ($categoryListLevel3 as $key2 => $value2) {
					 			if($value["cat_id"] == $value2["id"]){
					 				$categoryIdLevel3 = $value["cat_id"];
					 				unset($categoryPostList[$key]);
					 			}
					 		}
					 	}
				 	}

			 	}
			 	unset($where);
			 	PageUtil::addVar("title","แก้ไขประกาศ - Truck.co.th ตลาดซื้อขายรถบรรทุกและเครื่องจักรกลหนักทุกชนิด");
				$this->_assign('categories',$categories);
				$this->_assign("user_data", $this->ion_auth->user_array());
				$this->_fetch('form');exit;
			}else{
				show_404();
			}
		}else{
			$_post = $this->input->post();
			if(!empty($_post["submit"])){
				$_postmeta = $_post['meta'];

				if(empty($_post["id"])){
					$_post["url"] = Util::url_title(trim($_post["title"]));
					unset($where);
					$where["where"]["title"] = trim($_post["title"]);
					$isThere = $this->postModel->get($where);

					if(!empty($isThere)){
						$_post["url"] = Util::url_title(trim($_post["title"]))."-".count($isThere);
					}
					$_post["usr_id"] = $userdata["id"];
				}else{
					unset($where);
					$where["where"]["id"] = $_post["id"];
					$isThere = $this->postModel->get($where);
				}

				//Check and Set date for update post
				$start_date = new DateTime($isThere[0]["update_date"]);
				$start_date->add(new DateInterval("PT6H"));
				$now_date = new DateTime();
				if($start_date < $now_date){
					$_post["update_date"] = date( 'Y-m-d H:i:s');
				}

				$_post["cat_id"] = $_post["cat_id"][(count($_post["cat_id"])-1)];
				unset($where);
				
				$post_id = $this->postModel->add($_post);

				// make directory && check
				//check
				$path = "resource/".$post_id ;
				if(!file_exists($path)){
					mkdir('resource/'.$post_id, 0777, TRUE);
				}

				//load library image Manipulation for resize
				$this->load->library('image_lib');
				//load library upload
				$this->load->library('upload');
				//config
	 			$config['upload_path'] = $path ;
				$config['allowed_types'] = 'gif|jpg|png';
				$config['max_size']	= '102400';
				$config['max_width']  = '10240';
				$config['max_height']  = '7680';
				$config['encrypt_name'] = 'true';
				$this->upload->initialize($config);
				$totlecount = count($_FILES['filename']['name']);

				$groups = $_FILES['filename']['name'];

				foreach ($groups as $key => $group) {
					foreach ($group as $key2 => $item){
						if(!empty($_FILES['filename']['name'][$key][$key2])){
							$_FILES['userfile']['name']    = $_FILES['filename']['name'][$key][$key2];
							$_FILES['userfile']['type']    = $_FILES['filename']['type'][$key][$key2];
							$_FILES['userfile']['tmp_name'] = $_FILES['filename']['tmp_name'][$key][$key2];
		 					$_FILES['userfile']['error']       = $_FILES['filename']['error'][$key][$key2];
		 					$_FILES['userfile']['size']    = $_FILES['filename']['size'][$key][$key2];

							if (!$this->upload->do_upload()){
								log_message('error', $this->upload->display_errors());
							}else{

								$picturesData[$key][$key2] = $this->upload->data();
								

								$file_name = $picturesData[$key][$key2]["file_name"];
								//explode
								$image_name = explode(".", $file_name);

								$picturesData[$key][$key2]["large"] = $path."/".$image_name[0]."_mainSize.".$image_name[1];
								$picturesData[$key][$key2]["medium"] = $path."/".$image_name[0]."_mSize.".$image_name[1];
								$picturesData[$key][$key2]["small"] = $path."/".$image_name[0]."_sSize.".$image_name[1];


								//mainImage
								$config['image_library'] = 'GD2';
								// รูปที่เอามาใช้ในการ resize
								$config['source_image'] = $picturesData[$key][$key2]["full_path"];
								$config['maintain_ratio'] = TRUE;
								$config['quality'] = "70%";
								$config['new_image'] = $picturesData[$key][$key2]["large"];
								$config['width'] = 1024;
								$config['height'] = 680;
								$dim = (intval($picturesData[$key][$key2]["image_width"]) / intval($picturesData[$key][$key2]["image_height"])) - ($config['width'] / $config['height']);
								$config['master_dim'] = ($dim > 0) ? "height" : "width";
								$this->image_lib->clear();
								$this->image_lib->initialize($config);
								$this->image_lib->resize();

								//add water mark
								unset($config);
								$config['image_library'] = 'GD2';
								$config['source_image'] = $picturesData[$key][$key2]["large"];
								$config['wm_type'] = 'overlay';
								$config['wm_opacity'] = 100;
								$config['wm_overlay_path'] = "themes/".$this->config->item("theme_name").'/images/watermark.png';
								$config['wm_vrt_alignment'] = 'top';
								$config['wm_hor_alignment'] = 'right';
								$this->image_lib->clear();
								$this->image_lib->initialize($config);
								if(!$this->image_lib->watermark()){
									echo $this->image_lib->display_errors();exit;
								}
								unset($config);

								//mediumImage Resizing
								$config3['image_library'] = 'GD2';
								$config3['source_image'] = $picturesData[$key][$key2]["full_path"];
								$config3['new_image'] = $picturesData[$key][$key2]["medium"];
								$config3['maintain_ratio'] = TRUE;
								$config3['quality'] = "70%";
								$config3['width'] = 426;
								$config3['height'] = 328;
								$dim = (intval($picturesData[$key][$key2]["image_width"]) / intval($picturesData[$key][$key2]["image_height"])) - ($config3['width'] / $config3['height']);
								$config3['master_dim'] = ($dim > 0) ? "height" : "width";
								$this->image_lib->clear();
								$this->image_lib->initialize($config3);
								$this->image_lib->resize();

								$mediumImageDetail = $this->image_lib->get_image_properties($picturesData[$key][$key2]["medium"], TRUE);

								unset($config3);
								//mediumImage Cropping
								$config3['image_library'] = 'GD2';
								$config3['source_image'] = $picturesData[$key][$key2]["medium"];
								$config3['overwrite'] = TRUE;
								$config3['width'] = 426;
								$config3['height'] = 328;
								$config3['maintain_ratio'] = FALSE;
								//Set cropping for y or x axis, depending on image orientation
								if ($mediumImageDetail['width'] > $mediumImageDetail['height']) {
								  $config3['x_axis'] = (($mediumImageDetail['width'] / 2) - ($config3['width'] / 2));
								  $config3['y_axis'] = 0;
								}else{
									$config3['x_axis'] = 0;
								  $config3['y_axis'] = (($mediumImageDetail['height'] / 2) - ($config3['height'] / 2));
								}
								$this->image_lib->clear();
								$this->image_lib->initialize($config3);
								if (!$this->image_lib->crop()){
									log_message("error", "Image crop resize at [".__FILE__.":".__LINE__."]");
								}
								unset($config3);

								//add water mark
								unset($config);
								$config['image_library'] = 'GD2';
								$config['source_image'] = $picturesData[$key][$key2]["medium"];
								$config['wm_type'] = 'overlay';
								$config['wm_opacity'] = 100;
								$config['wm_overlay_path'] = "themes/".$this->config->item("theme_name").'/images/watermark-m.png';
								$config['wm_vrt_alignment'] = 'top';
								$config['wm_hor_alignment'] = 'right';
								$this->image_lib->clear();
								$this->image_lib->initialize($config);
								$this->image_lib->watermark();
								unset($config);

								//resize smallImage
								$config2['image_library'] = 'GD2';
								$config2['source_image'] = $picturesData[$key][$key2]["full_path"];
								$config2['new_image'] = $picturesData[$key][$key2]["small"];
								$config2['maintain_ratio'] = TRUE;
								$config2['quality'] = "70%";
								$config2['width'] = 110;
								$config2['height'] = 95;
								$dim = (intval($picturesData[$key][$key2]["image_width"]) / intval($picturesData[$key][$key2]["image_height"])) - ($config2['width'] / $config2['height']);
								$config2['master_dim'] = ($dim > 0) ? "height" : "width";
								$this->image_lib->clear();
								$this->image_lib->initialize($config2);
								if(!$smallImageResult = $this->image_lib->resize()){
									log_message("error", "Image can't resize at [".__FILE__.":".__LINE__."]");
								}

								$smallImageDetail = $this->image_lib->get_image_properties($picturesData[$key][$key2]["small"], TRUE);

								unset($config2);
								//mediumImage Cropping
								$config2['image_library'] = 'GD2';
								$config2['source_image'] = $picturesData[$key][$key2]["small"];
								$config2['overwrite'] = TRUE;
								$config2['quality'] = "60%";
								$config2['width'] = 110;
								$config2['height'] = 95;
								$config2['maintain_ratio'] = FALSE;
								//Set cropping for y or x axis, depending on image orientation
								if ($smallImageDetail['width'] > $smallImageDetail['height']) {
								  $config2['x_axis'] = (($smallImageDetail['width'] / 2) - ($config2['width'] / 2));
								  $config2['y_axis'] = 0;
								}else{
									$config2['x_axis'] = 0;
								  $config2['y_axis'] = (($smallImageDetail['height'] / 2) - ($config2['height'] / 2));
								}
								$this->image_lib->clear();
								$this->image_lib->initialize($config2);
								if (!$this->image_lib->crop()){
									log_message("error", "Image crop resize at [".__FILE__.":".__LINE__."]");
								}
								unset($config2);

								//add water mark
								unset($config);
								$config['image_library'] = 'GD2';
								$config['source_image'] = $picturesData[$key][$key2]["full_path"];
								$config['wm_type'] = 'overlay';
								$config['wm_opacity'] = 100;
								$config['wm_overlay_path'] = "themes/".$this->config->item("theme_name").'/images/watermark.png';
								$config['wm_vrt_alignment'] = 'top';
								$config['wm_hor_alignment'] = 'right';
								$this->image_lib->clear();
								$this->image_lib->initialize($config);
								if(!$this->image_lib->watermark()){
									echo $this->image_lib->display_errors();exit;
								}
								unset($config);
							}
						}
					}
				}

				$postcode['code'] = sprintf("%06s", $post_id);
				$postcode['id'] =  $post_id;
				$this->postModel->add($postcode);

				$this->load->model("category_post_model","categoryPostModel");
				$categoryList = Util::getCategoryInherit($_post["cat_id"],NULL);

				$whereDelCatPost["where"]["pos_id"] = $post_id;
				$catPostResult = $this->categoryPostModel->delete($whereDelCatPost);
				foreach ($categoryList as $categoryListKey => $categoryListValue) {
					$setCatPost["cat_id"] = $categoryListValue["id"];
					$setCatPost["pos_id"] = $post_id;
					$catAddPostResult[] = $this->categoryPostModel->add($setCatPost);
				}

				$this->load->model("postmeta_model","postmetaModel");

				foreach ($_postmeta as $key => $value) {
					$where['where']['pos_id'] = $post_id;
					$where['where']['key'] = $key;
					$posID = $this->postmetaModel->get($where);
					if($posID){
						$_postmeta['key'] = $key;
						$_postmeta['value'] = $value;
						$_postmeta['pos_id'] = $post_id;
						$_postmeta['id'] = $posID[0]["id"];
					}else{
						$_postmeta['key'] = $key;
						$_postmeta['value'] = $value;
						$_postmeta['pos_id'] = $post_id;
					}
					$updatedItem[] = $this->postmetaModel->add($_postmeta);
					unset($_postmeta);
				}

				if(!empty($updatedItem)){
					$whereDeleteItem["where_not_in"]["id"] = $updatedItem;
					$whereDeleteItem["where"]["pos_id"] = $post_id;
					$deleteItems = $this->postmetaModel->get($whereDeleteItem);
					if(!empty($deleteItems)){
						foreach ($deleteItems as $key => $value) {
							$this->postmetaModel->delete($value["id"]);
						}
					}
				}

				if($post_id){
					$whereGetImages["where"]["pos_id"] = $post_id;
					$resultGetImages = $this->imagesModel->get($whereGetImages);
					if(empty($_post["id"]) OR empty($resultGetImages)){
						$first_image = FALSE;
					}else{
						$first_image = TRUE;
					}
					if(!empty($picturesData)){
						foreach ($picturesData as $key3 => $group2) {
						 	foreach ($group2 as $key4 => $value) {
						 		$this->load->model("images_model","imagesModel");
						 		$image['group'] = $key3;
						 		$image['pos_id'] = $post_id;
						 		$image['filesize'] = $value["file_size"];
						 		$image['type'] = $value["image_type"];
						 		$image['filename'] = $value["file_name"];
						 		$image['filepath'] = $path."/".$value["file_name"];
						 		$image['large'] = $value["large"];
						 		$image['medium'] = $value["medium"];
						 		$image['small'] = $value["small"];
						 		if(!$first_image){
						 			$image['firstimage'] = 1;
						 			$first_image = TRUE;
						 		}else{
						 			$image['firstimage'] = 0;
						 		}
						 		$this->imagesModel->add($image);
						 	}
						}
					}
					if(!empty($_post["id"])){
						$postUrl = $isThere[0]["url"];
					}else{
						$postUrl = $_post["url"];
					}

					$this->cache->delete_group('post_');
					$this->cache->delete_folder('postview/postview_'.md5(urlencode($postUrl)));

					redirect(base_url("post/view/".urlencode($postUrl)),"refresh");
					die;
				}
			}else{
				PageUtil::addVar("title","ลงประกาศใหม่ - Truck.co.th ตลาดซื้อขายรถบรรทุกและเครื่องจักรกลหนักทุกชนิด");
				$this->load->model("brand_model","brandModel");
				$where['order'] = "id ASC";
				$brands = $this->brandModel->get($where);
				$this->_assign("brands",$brands);
				$this->load->model('category_model','categoryModel');
				$where["where"]["parent_id"] = 0;
				$where["order"] = "sort ASC";
			 	$result = $this->categoryModel->get($where);
			 	foreach ($result as $key => $value) {
			    $categories[0]['items'][$value['id']] = $value;
			    $categories[0]['parents'][$value['parent_id']][] = $value['id'];
			 	}
				$this->_assign('categories',$categories);
				$this->load->model('type_model','typeModel');

				$whereType['order'] = "id ASC";
				$type = $this->typeModel->get($whereType);
				$this->_assign('types',$type);
				$this->_assign("user_data", $this->ion_auth->user_array());

				$this->_fetch('form');
			}
		}
	}

	function del($id = ""){
		if(!$this->ion_auth->logged_in()){
			redirect(base_url("user/login"),"refresh");
		}
		if(empty($id)){
			redirect(base_url(),"refresh");
		}
		$userdata = $this->ion_auth->user_array();
		$result = $this->postModel->get($id);

		if($result[0]["usr_id"] == $userdata['id'] OR $this->ion_auth->in_group("admin")){
			$delete["id"] = $id;
			$delete["status"] = 0;
			$result = $this->postModel->add($delete);
			$this->cache->delete_group('post_');
		}else{
			show_404();
		}
		redirect('post');
	}

	function my(){
		if(!$this->ion_auth->logged_in()){
			redirect(base_url("user/login"),"refresh");
		}
		$userdata = $this->ion_auth->user_array();
		if(!$posts = $this->cache->get("post_user_".mb_strtolower($userdata["username"]))){
			$user_id = $userdata["id"];
			$this->load->model('post_model','postModel');
			$this->load->model('images_model','imagesModel');
			$where['where']['usr_id'] = $user_id;
			$posts = $this->postModel->get($where);
			if(!empty($posts)){
				foreach ($posts as $key => $value) {
					$posts[$key]["images"] = $this->imagesModel->get(array("where"=>array("pos_id"=>$value["id"])));
					$posts[$key]["categories"] = array_reverse(Util::getCategoryInherit($value["cat_id"]));
					$posts[$key]["province"] = Util::getProvince($posts[$key]["province"]);
					$posts[$key]["meta"] = Util::getPostMeta($posts[$key]["id"]);
					$posts[$key]["comment_count"] = Util::getCommentCount($posts[$key]["id"]);
					$posts[$key]["type"] = Util::getType($posts[$key]["typ_id"]);
				}
			}
			$this->cache->write($posts,"post_user_".mb_strtolower($userdata["username"]),(3600*24));
		}
		$this->_assign('posts',$posts);

		PageUtil::addVar("title","ประกาศของคุณ ".$posts[0]['firstname']." ".$posts[0]['lastname']." - Truck.co.th ตลาดซื้อขายรถบรรทุกและเครื่องจักรกลหนักทุกชนิด");
 		
		$this->_fetch('mycontent');
	}


	function user($username = NULL){
		if(empty($username)){
			show_404();
		}
		if(!$posID = $this->cache->get("post_user_".mb_strtolower($username))){
			$this->load->model('post_model','postModel');
	 		$this->load->model('images_model','imagesModel');
	 		$user = $this->ion_auth->username($username);
	 		if(empty($user)){
	 			show_404();
	 		}

	 		$where['where']['usr_id'] = $user[0]['id'];
			$posID = $this->postModel->get($where);

			if(!empty($posID)){
				foreach ($posID as $key => $value) {
					$posID[$key]["images"] = $this->imagesModel->get(array("where"=>array("pos_id"=>$value["id"])));
					$posID[$key]["categories"] = array_reverse(Util::getCategoryInherit($value["cat_id"]));
					$posID[$key]["province"] = Util::getProvince($posID[$key]["province"]);
					$posID[$key]["meta"] = Util::getPostMeta($posID[$key]["id"]);
					$posID[$key]["comment_count"] = Util::getCommentCount($posID[$key]["id"]);
					$posID[$key]["type"] = Util::getType($posID[$key]["typ_id"]);
				}
			}
			$this->cache->write($posID,"post_user_".mb_strtolower($username),(3600*24));
		}

		PageUtil::addVar("title","ประกาศของคุณ ".$posID[0]['firstname']." ".$posID[0]['lastname']." - Truck.co.th ตลาดซื้อขายรถบรรทุกและเครื่องจักรกลหนักทุกชนิด");
 		
		$this->_assign('postcontents',$posID);
		//var_dump($posID); exit();
		$this->_fetch('usercontent');
	}


	function ajax_getmodel(){
		if(!IS_AJAX){
			show_404();
		}
		if(!$this->ion_auth->logged_in()){
			show_404();
		}
		$this->load->model("model_model","modelModel");
		$_post = $this->input->post();
		$where['where']['brand_id'] = $_post["brand_id"];
		$where["order"] = 'CONVERT( mod_name USING tis620 ) ASC';
		$model = $this->modelModel->get($where);
		$this->_assign("model",$model);
		$this->_fetch("ajax_getmodel","",FALSE,TRUE);
	}

	function ajax_getbrand(){
		if(!IS_AJAX){
			show_404();
		}
		if(!$this->ion_auth->logged_in()){
			show_404();
		}
		$this->load->model("category_brand_model","categoryBrandModel");
		$_post = $this->input->post();
		$where['where']['category_id'] = $_post["cat_id"];
		$where["order"] = 'CONVERT( brand_name USING tis620 ) ASC';
		$where["group"] = 'brand_id';
		$brand = $this->categoryBrandModel->get($where);
		$this->_assign("brands",$brand);
		$this->_fetch("ajax_getbrand","",FALSE,TRUE);
	}

	function ajax_getchildcategory(){
		if(!IS_AJAX){
			show_404();
		}
		if(!$this->ion_auth->logged_in()){
			show_404();
		}
		$_post = $this->input->post();

		//Cache check
		if($categories = $this->cache->get("category/category_ajax_getchildcategory_".$_post["parent_id"])){
			echo json_encode($categories); die;
		}
		$this->load->model("category_model","categoryModel");
		$categories = Util::getSubCategory($_post["parent_id"]);

		//Cache Write
		$this->cache->write($categories,"category/category_ajax_getchildcategory_".$_post["parent_id"], 0);
		echo json_encode($categories); die;
	}

	function delete_image($id = NULL){
		if(!$this->ion_auth->logged_in()){
			show_404();
		}

		if(empty($id)){
			show_404();
		}

		$image_id = $id;
		$this->load->model("images_model","imagesModel");
		$where['where']['id'] = $image_id;
		$detail_image = $this->imagesModel->get($where);

		$resultPost = $this->postModel->get($detail_image[0]["pos_id"]);
		$userdata = $this->ion_auth->user_array();

		if($resultPost[0]['usr_id'] == $userdata['id'] OR $this->ion_auth->in_group("admin"))
		{
			if(!empty($detail_image)){
				if(file_exists($detail_image[0]["filepath"])){
					@unlink($detail_image[0]["filepath"]);
				}
				if(file_exists($detail_image[0]["large"])){
					@unlink($detail_image[0]["large"]);
				}
				if(file_exists($detail_image[0]["medium"])){
					@unlink($detail_image[0]["medium"]);
				}
				if(file_exists($detail_image[0]["small"])){
					@unlink($detail_image[0]["small"]);
				}
				$this->imagesModel->delete($image_id);
			}
		}
		redirect(base_url("post/add/".$detail_image[0]["pos_id"]));
	}

	function check_type($id = NULL, $type = NULL){
		if(!$this->ion_auth->logged_in()){
			show_404();
		}
		if(empty($id)){
			show_404();
		}
		if(empty($type)){
			show_404();
		}
		$this->load->model('post_model','postModel');
		$resultpost = $this->postModel->get($id);
		$userdata = $this->ion_auth->user_array();

		if($resultpost[0]['usr_id'] == $userdata['id'] OR $this->ion_auth->in_group("admin"))
		{
			if($type =="9"){
				$chengtyp_id['id'] = $id;
				$chengtyp_id['typ_id'] =$type;
				$this->postModel->add($chengtyp_id);
			}elseif($type =="10"){
				$chengtyp_id['id'] = $id;
				$chengtyp_id['typ_id'] = $type;
				$this->postModel->add($chengtyp_id);
			}elseif( $type =="0"  AND ($resultpost[0]['typ_id'] == 9 OR $resultpost[0]['typ_id'] ==10)){
				$chengtyp_id['id'] = $id;
				$chengtyp_id['typ_id'] = $type;
				$this->postModel->add($chengtyp_id);
			}
		}
		redirect(base_url("post/view/".urlencode($resultpost[0]['url'])),"refresh");
	}



	function updatepost($id = NULL){
		if(!$this->ion_auth->logged_in()){
			show_404();
		}
		if(empty($id)){
			show_404();
		}
		$this->load->model('post_model','postModel');
		$resultPost = $this->postModel->get($id);
		$userdata = $this->ion_auth->user_array();

		if($resultPost[0]['usr_id'] == $userdata['id'] OR $this->ion_auth->in_group("admin"))
		{
			$start_date = new DateTime($resultPost[0]["update_date"]);
			$start_date->add(new DateInterval("PT6H"));
			$now_date = new DateTime();
			if($start_date < $now_date){
				$data["id"] = $resultPost[0]["id"];
				$data["update_date"] = date( 'Y-m-d H:i:s');
				$this->postModel->add($data);
			}
		}
		redirect(base_url("post/view/".urlencode($resultPost[0]['url'])),"refresh");
	}

}